﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint.StsAdmin;
using System.Text;
using Microsoft.SharePoint;
using System.Collections.Specialized;
using System.IO;
using System.Globalization;

namespace Macaw.Moss2007.CustomErrorPageSolution
{
    public class SetCustomErrorPageStsAdmExtension : ISPStsadmCommand
    {

        public string GetHelpMessage(string command)
        {
            return "-url <url of web modify (rootweb or subweb)> -errorpageurl <url of the error page>";
        }

        public int Run(string command, StringDictionary keyValues, out string output)
        {

            return SetCustomErrorPage(keyValues, out output);
        }


        private int SetCustomErrorPage(StringDictionary keyValues, out string output)
        {
            output = "Something went wrong!";


            if (!keyValues.ContainsKey("url"))
            {
                output = "The 'url' parameter was not specified.";
                return -1;
            }
            String url = keyValues["url"];

            if (!keyValues.ContainsKey("errorpageurl"))
            {
                output = GetHelpMessage("") + "\r\nThe 'errorpageurl' parameter was not specified.";
                return -1;
            }
            String errorpageurl = keyValues["errorpageurl"];


            try
            {
                using (var siteCollection = new SPSite(url))
                {
                    using (var webSite = siteCollection.OpenWeb())
                    {
                        CustomErrorPageHelper.SetCustomErrorPageUrl(webSite, errorpageurl);
                    }

                }
                output = "done";
                return 0;
            }
            catch (Exception ex)
            {
                output = ex.Message;
            }
            return -1;
        }

    }
}
